// -*-mode:c++; coding:utf-8-*-

#ifndef _XBASE_SCANNER_CHECKER_HPP_
#define _XBASE_SCANNER_CHECKER_HPP_

#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/noncopyable.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include "global.hpp"
#include "kv_scanner_manager.hpp"

namespace xbase
{
	class scanner_checker
		: private boost::noncopyable
	{
	public:
		scanner_checker()
			: m_io_service()
			, m_timer(m_io_service)
			, m_duration(global::the_conf->scanner_check_interval) {
			set_timer();
		}

		void run() {
			LOG(INFO, "scanner_checker::run checker started");
			m_io_service.run();
		}

		void stop() {
			m_io_service.stop();
		}

	protected:
		void set_timer() {
			m_timer.expires_from_now(m_duration);
			m_timer.async_wait(boost::bind(&scanner_checker::check, this));
		}
		
		void check() {
			LOG(INFO, "scanner_checker::check check expired scanners");
			global::the_scanner_manager->close_expired_scanners(global::the_conf->scanner_lifetime);
			set_timer();
			LOG(INFO, "scanner_checker::check checking done");
		}

	private:
		boost::asio::io_service m_io_service;
		boost::asio::deadline_timer m_timer;
		boost::posix_time::seconds m_duration;
	};

} // namespace xbase

#endif	// _XBASE_SCANNER_CHECKER_HPP_
